package com.siqi.hr.common.controller;

import com.alibaba.fastjson.JSON;
import com.siqi.hr.common.Constants;
import com.siqi.hr.system.common.model.ReturnInfo;
import com.siqi.hr.system.organization.entity.Employee;
import com.siqi.hr.system.organization.service.EmployeeService;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.Date;

/**
 * @Title:思齐教育财务系统
 * @Description: 通过url获取前台用户信息
 * @Copyright: Copyright (c) 2016
 * @Company: 思齐教育集团
 * @author: ChenLei
 * @version: 1.0.0.0
 * @Date: 2016年5月3日
 */
@Controller
@RequestMapping(value="authorize")
public class Authorize {

	@Autowired
	private EmployeeService employeeService;

	/**
	 * 获取url用户登录信息
	 * @param httpRequest
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="urlLogin")
	public String index(HttpServletRequest httpRequest, HttpSession session) throws Exception{
		String token = httpRequest.getParameter("token");
		//创建HttpClient实例
		DefaultHttpClient httpclient = new DefaultHttpClient();
		//创建get方法实例
		HttpGet httpgets = new HttpGet(Constants.P_URL_TOKEN);
		BasicHeader header = new BasicHeader("Cookie","token="+token);
		httpgets.addHeader(header);
		String failureUrl = "error/500";
		String successUrl = "redirect:/Employee/loginModule.do?moduleid=";
		HttpResponse response = httpclient.execute(httpgets);
		HttpEntity entity = response.getEntity();
		if(null != entity & 401 != response.getStatusLine().getStatusCode()){
			InputStream instreams = entity.getContent();
			BufferedReader reader = new BufferedReader(new InputStreamReader(instreams,"utf-8"));    
			
	        StringBuilder sb = new StringBuilder();      
	       
	        String line = null;      
	        try {      
	            while ((line = reader.readLine()) != null) {  
	                sb.append(line + "\n");     
	                
	            }      
	        } catch (IOException e) {      
	            e.printStackTrace();      
	        } finally {      
	            try {      
	            	instreams.close();      
	            } catch (IOException e) {      
	               e.printStackTrace();      
	            }      
	        }

	        System.out.print(sb.toString());
			Users author = JSON.parseObject(sb.toString(), Users.class);
			httpRequest.getSession().setAttribute("pSiqiUser",author);
			Employee employee = new Employee();
			employee.setJobNumber(author.getUserName());
			String pwd = employee.getPassword() == null ? "" : employee.getPassword();
			employee.setPassword(pwd);
			session.setMaxInactiveInterval(60*60*1);  // 设置Session有效时间为1小时
			//验证登陆用户名、密码是否正确
			ReturnInfo info = employeeService.checkLogin(httpRequest,session,employee);
			if(info.isSuccess()){
				System.out.println("用户名为："+author.getUserName());
				System.out.println("登录时间：" + new Date());
				successUrl += info.getModule().getId();
				return successUrl;
			}else {
				return failureUrl;
			}
		}
		return failureUrl;
	}

	@RequestMapping(value = "chekUrlLogin")
	public void chekUrlLogin(HttpServletRequest request, PrintWriter printWriter){
		String sessionCode = request.getParameter("sessionCode");
		if(StringUtils.isNotBlank(sessionCode)){
			Users author = (Users) request.getSession().getAttribute("pSiqiUser");
			if (author != null){
				printWriter.print(JSON.toJSONString(author));
			}else {
				printWriter.print(JSON.toJSONString(new Users()));
			}
		}else {
			printWriter.print(JSON.toJSONString(new Users()));
		}
	}
}
